#include "replacerulesdelegate.h"
#include <QLineEdit>
#include <QComboBox>

ReplaceRulesDelegate::ReplaceRulesDelegate(QObject *parent) :
    QItemDelegate(parent)
{
}

void ReplaceRulesDelegate::paint(QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index){
    QItemDelegate::paint(painter,option,index);
}

QWidget *ReplaceRulesDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
    int c = index.column();
    if(c==0){
        QComboBox *comboBox = new QComboBox(parent);
        comboBox->addItem("FixedString");
        comboBox->addItem("Wildcard");
        comboBox->addItem("WildcardUnix");
        comboBox->addItem("RegExp");
        comboBox->addItem("RegExp2");
        connect(comboBox,SIGNAL(activated(int)),this,SLOT(commitAndCloseEditor(int)));
        return comboBox;
    }
    else if((c==1)||(c==2)){
        QLineEdit *lineEdit = new QLineEdit(parent);
        connect(lineEdit,SIGNAL(editingFinished()),this,SLOT(commitAndCloseEditor()));
        return lineEdit;
    }
    else {
        return QItemDelegate::createEditor(parent,option,index);
    }
}

void ReplaceRulesDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{
    int c = index.column();
    QString str = index.model()->data(index,Qt::DisplayRole).toString();
    if(c==0){
        QComboBox* comboBox = qobject_cast<QComboBox*>(editor);
        comboBox->setEditText(str);
    }
    else if(c==1){
        QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
        lineEdit->setText(str);
    }
    else if(c==2){
        QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
        lineEdit->setText(str);
    }
    else{
        QItemDelegate::setEditorData(editor,index);
    }
}

void ReplaceRulesDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{

    int c = index.column();
    if(c==0){
        QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
        model->setData(index,comboBox->currentText());
    }
    else if((c==1)||(c==2)){
        QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
        model->setData(index,lineEdit->text());
    }
    else{
        QItemDelegate::setModelData(editor,model,index);
    }
}

void ReplaceRulesDelegate::commitAndCloseEditor(){
    QLineEdit *editor = qobject_cast<QLineEdit *>(sender());
    emit commitData(editor);
    emit closeEditor(editor);
}

void ReplaceRulesDelegate::commitAndCloseEditor(int){
    QComboBox *editor = qobject_cast<QComboBox *>(sender());
    emit commitData(editor);
    emit closeEditor(editor);
}
